package com.sch.wanandroid.ui.regist

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.sch.wanandroid.network.NetWorkManager
import kotlinx.coroutines.launch

/**
 * Created by Sch.
 * Date: 2020/12/15
 * description:
 */
class RegistViewModel : ViewModel() {
    val userName = MutableLiveData<String>().apply {
        value = ""
    }
    val passWord = MutableLiveData<String>().apply {
        value = ""
    }
    val rePassword = MutableLiveData<String>().apply {
        value = ""
    }

    private val _registSuccess = MutableLiveData<Boolean>()
    val registSuccessLiveData: LiveData<Boolean> = _registSuccess

    private val _errorMsg = MutableLiveData<String?>()
    val errorMsg: LiveData<String?> = _errorMsg

    fun doRegister() {
        viewModelScope.launch {
            try {
                val result = NetWorkManager.apiService.doRegister(
                    userName.value!!,
                    passWord.value!!,
                    rePassword.value!!
                )
                if (result.errorCode != 0) {
                    _errorMsg.value = result.errorMsg
                } else {
                    _registSuccess.value = true
                }
            } catch (e: Exception) {
                _errorMsg.value = e.toString()
            }
        }
    }
}